<!--角色管理-->
<!--created by lx 2023/2/20-->
<!--created by yuyupeng 2023/4/19-->
<template>
  <div class="list-card-container">
    <a-card title="角色管理" class="general-card">
      <!-- 查询表单 -->
      <table-search :data-source="SEARCH_FORM" @change="searchRole" />

      <!-- 表格 -->
      <AdvancedDrawer
        v-permission="['system:role:add']"
        clickword="新增"
        title="新增菜单"
        :data-source="ADD_FORM"
        narrow
        style="margin-bottom: 16px"
        @change="addRole"
      />
      <a-table
        :columns="COLUMNS_ROLE"
        :data="roleList"
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
      >
        <!-- 插槽：状态 -->
        <template #status="{ record }">
          <a-tag v-if="record.status === 0" color="#00b42a">正常</a-tag>
          <a-tag v-if="record.status === 1" color="#86909c">停用</a-tag>
        </template>
        <!--插槽，操作-->
        <template #operation="{ record }">
          <a-space
            v-permission="[
              'system:role:menu-auth',
              'system:role:edit',
              'system:role:delete',
            ]"
          >
            <AuthDrawer
              v-permission="['system:role:menu-auth']"
              :role-id="record.id"
            />
            <a-link
              v-permission="['system:role:data-auth']"
              @click="showDataAuthTree(record)"
              >数据授权</a-link
            >
            <AdvancedDrawer
              v-permission="['system:role:edit']"
              :data-source="EDIT_FORM"
              :data-record="record"
              clickword="修改"
              title="修改"
              click="link"
              narrow
              icon="empty"
              @change="(req) => editRole(req, record)"
            />
            <a-popconfirm
              type="warning"
              content="确认删除此角色？"
              @ok="deleteRole(record)"
            >
              <a-link v-permission="['system:role:delete']">删除</a-link>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 数据权限抽屉 -->
    <AdvancedDrawer
      ref="dataAuthTreeDrawerRef"
      click="link"
      title="数据授权"
      clickword=""
      :narrow="true"
      :rules="DataAuthTreeRules"
      :data-source="DataAuthTreeConfig"
      :data-record="currentRecord"
      @dictionary="dictionaryChange"
      @change="dataAuthTreeSubmit"
    >
      <template v-if="currentDataScope === '2'" #deptIds>
        <DataAuthTree
          ref="dataAuthTreeRef"
          :data-scope-dept-ids="currentRecord?.dataScopeDeptIds || []"
          @change="dataAuthTreeChange"
        />
      </template>
    </AdvancedDrawer>
  </div>
</template>

<script lang="ts">
  import { Message, TableColumnData, Notification } from '@arco-design/web-vue';
  import {
    RoleRecord,
    RoleParams,
    DataAuthParam,
  } from '@/api/system/model/roleModel';
  import {
    queryRoleRecordPage,
    saveRoleRecord,
    updateRoleRecord,
    deleteRoleRecord,
    updateRoleDataAuth,
  } from '@/api/system/role';
  import { defineComponent, ref, onMounted, reactive, nextTick } from 'vue';
  import { Pagination } from '@/types/global';
  import TableSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  import AuthDrawer from './components/auth-drawer.vue';
  import DataAuthTree from './components/data-auth-tree.vue';

  export default defineComponent({
    components: { TableSearch, AdvancedDrawer, AuthDrawer, DataAuthTree },
    setup() {
      // 查询表单
      const SEARCH_FORM: any[] = [
        { fieldName: 'name', labelText: '角色', type: 'text' },
        { fieldName: 'code', labelText: '角色编码', type: 'text' },
      ];

      const loading = ref<boolean>(false);

      // func: 查询角色
      const searchRole = async (
        params: RoleParams = {
          page: 1,
          limit: 10,
        }
      ) => {
        loading.value = true;
        try {
          const { data } = await queryRoleRecordPage(params);
          roleList.value = data.list;
          pagination.total = data.total;
          pagination.current = params.page;
        } finally {
          loading.value = false;
        }
        // 从try到finally的部分 =
        // queryUwerRecordList(params).then(res) => {
        //   const { data } = res;
        //   roleList.value = data.list;
        //   pagination.total = data.total;
        // }
      };

      onMounted(() => {
        searchRole();
      });

      // 表格
      const roleList = ref<RoleRecord[]>([]);
      const COLUMNS_ROLE: TableColumnData[] = [
        {
          title: '序号',
          align: 'center',
          dataIndex: 'index',
          render: ({ rowIndex }) => rowIndex + 1,
        },
        { title: '状态', dataIndex: 'status', slotName: 'status' },
        { title: '角色名称', dataIndex: 'name' },
        { title: '角色编码', dataIndex: 'code' },
        // { title: '角色类别', dataIndex: 'type' },
        { title: '备注', dataIndex: 'remark' },
        {
          title: '操作',
          dataIndex: 'operation',
          slotName: 'operation',
          width: 280,
          align: 'center',
        },
      ];
      const currentRecord = ref<RoleRecord>(); // 记录当前选择的表格行
      const currentDataScope = ref<string>(); // 记录数据权限抽屉中当前选择的权限范围
      const currentDataScopeDeptIds = ref<string[]>([]); // 记录当前选择的表格行
      const dataAuthTreeDrawerRef = ref<any>();
      const dataAuthTreeRef = ref<any>();

      // 分页
      const basePagination: Pagination = {
        current: 1,
        pageSize: 10,
        showPageSize: false,
        showTotal: false,
      };
      const pagination = reactive({
        ...basePagination,
      });
      const onPageChange = (current: number) => {
        searchRole({
          limit: pagination.pageSize,
          page: current,
        });
      };

      // 表单选择器：状态
      const STATUS_OPTIONS: { label: string; value: number }[] = [
        { label: '正常', value: 0 },
        { label: '停用', value: 1 },
      ];

      // 抽屉：新增角色
      const ADD_FORM: any[] = [
        { labelText: '角色名称', fieldName: 'name', col: 24, required: true },
        { labelText: '角色编码', fieldName: 'code', col: 24, required: true },
        {
          type: 'select',
          labelText: '状态',
          allowSearch: false,
          fieldName: 'status',
          codefield: 'value',
          namefield: 'label',
          options: STATUS_OPTIONS,
          initialValue: 0,
          col: 24,
          required: true,
        },
        {
          labelText: '备注',
          fieldName: 'remark',
          col: 24,
          textrow: 4,
        },
      ];
      // 抽屉：数据权限
      const DataAuthTreeConfig = [
        { type: 'text', labelText: '', fieldName: 'id', visible: false },
        {
          col: 24,
          type: 'text',
          labelText: '角色名称',
          fieldName: 'name',
          disabled: true,
        },
        {
          col: 24,
          type: 'text',
          labelText: '角色编码',
          fieldName: 'code',
          disabled: true,
        },
        {
          col: 24,
          type: 'dictionary',
          dictType: 'dataAuthScope',
          labelText: '权限范围',
          fieldName: 'dataScope',
        },
        { col: 24, type: 'other', labelText: '', fieldName: 'deptIds' },
      ];
      // 数据权限抽屉表单项校验配置
      const DataAuthTreeRules = ref({
        dataScope: [{ required: true, message: '请选择权限范围' }],
      });

      // func: 新增角色
      const addRole = async (req: RoleRecord) => {
        try {
          await saveRoleRecord(req);
          Message.success('新增成功');
        } finally {
          searchRole();
        }
      };

      // 抽屉：编辑
      const EDIT_FORM: any[] = [
        { labelText: '角色名称', fieldName: 'name', col: 24, required: true },
        { labelText: '角色编码', fieldName: 'code', col: 24, required: true },
        {
          type: 'select',
          labelText: '状态',
          allowSearch: false,
          fieldName: 'status',
          codefield: 'value',
          namefield: 'label',
          options: STATUS_OPTIONS,
          col: 24,
          required: true,
        },
        {
          labelText: '备注',
          fieldName: 'remark',
          col: 24,
          textrow: 4,
        },
      ];

      // func: 编辑角色
      const editRole = async (req: RoleRecord, record: RoleRecord) => {
        try {
          await updateRoleRecord({
            ...req,
            id: record.id,
          });
          Message.success('修改成功');
        } finally {
          searchRole();
        }
      };

      // func: 删除角色
      const deleteRole = async (row: RoleRecord) => {
        try {
          await deleteRoleRecord(row.id as string);
          Message.success('删除成功');
        } finally {
          searchRole();
        }
      };

      /**
       * @description 打开数据权限抽屉
       * @param record 当前选择的表格行数据
       */
      const showDataAuthTree = (record: RoleRecord) => {
        record.dataScope = String(record.dataScope); // 要转成String，因为数据字典组件识别不出来number类型
        currentRecord.value = record;
        currentDataScope.value = record.dataScope;
        currentDataScopeDeptIds.value = record.dataScopeDeptIds as string[];
        dataAuthTreeDrawerRef.value.showDrawer(); // 打开数据权限抽屉
        if (record.dataScope === '2') {
          // value为2说明是指定部门数据权限
          nextTick(() => {
            dataAuthTreeRef.value.getDeptTree();
          });
        }
      };

      /**
       * @description 数据权限部门树勾选变化触发
       * @param deptIds
       */
      const dataAuthTreeChange = (deptIds: string[]) => {
        currentDataScopeDeptIds.value = deptIds;
      };

      /**
       * @method
       * @description 配置数据权限
       */
      const dataAuthTreeSubmit = async (reqdata: any) => {
        console.log(reqdata);
        const req = {} as DataAuthParam;
        req.roleId = reqdata.id;
        req.dataScope = reqdata.dataScope;
        if (req.dataScope === '2') {
          // 如果是‘2’说明是指定部门数据权限
          req.dataScopeDeptIds = currentDataScopeDeptIds.value;
        }
        try {
          const res = (await updateRoleDataAuth(req)) as any;
          console.log(res);
          if (res.code === 200) {
            Notification.success({
              content: '修改成功！',
            });
          } else {
            Notification.error({
              title: '修改失败！',
              content: res.message,
            });
          }
        } catch (error) {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          Notification.error({
            content: `出现异常！${error}`,
            closable: true,
          });
        } finally {
          searchRole();
        }
      };

      /**
       * @description 数据权限抽屉中的权限范围发生变化触发
       * @param value
       * @param name
       */
      const dictionaryChange = (value: string) => {
        currentDataScope.value = value;
        if (value === '2') {
          // value为2说明是指定部门数据权限
          nextTick(() => {
            dataAuthTreeRef.value.getDeptTree();
          });
        }
      };

      return {
        // 查询
        SEARCH_FORM,
        searchRole,

        // 表格
        COLUMNS_ROLE,
        roleList,
        pagination,
        onPageChange,
        loading,
        editRole,
        deleteRole,
        currentRecord,
        currentDataScope,
        dataAuthTreeDrawerRef,
        dataAuthTreeRef,

        // 抽屉：新增
        addRole,
        ADD_FORM,

        // 抽屉：数据权限
        DataAuthTreeConfig,
        DataAuthTreeRules,
        showDataAuthTree,
        dataAuthTreeChange,
        dataAuthTreeSubmit,
        dictionaryChange,

        // 抽屉：修改
        EDIT_FORM,
      };
    },
  });
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    // background-color: var(--color-bg-1);
    border-radius: var(--border-radius-default);
  }
</style>
